package org.osoftware.mumi.web.controller;

import java.io.IOException;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.osoftware.mumi.service.business.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@ManagedBean
@RequestScoped
@Component
public class LoginBean extends BaseFormBean{
	

	@Autowired
	private SecurityService securityService;
	
	private String userName;
	private String password;
	
	public void save(ActionEvent event) {
		UserDetails ud = securityService.loadUserByUsername("111");
		if (ud.getPassword().equals(password))
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("You've registered"));
		else
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Password incorrecto"));
	}
	
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	
	
	
	

	public String doLogin() throws ServletException, IOException {
		ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
		RequestDispatcher dispatcher= ((ServletRequest)context.getRequest()).getRequestDispatcher("/j_spring_security_check");
		dispatcher.forward((ServletRequest)context.getRequest(), (ServletResponse)context.getResponse());
		FacesContext.getCurrentInstance().responseComplete();
		return null;
	}
	
	public String doLogout() {
		FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
		return "index.xhtml";
	}
}
